package cn.sciento.starter.tenant.custom.core;

import java.lang.reflect.Method;
import org.apache.commons.lang3.reflect.MethodUtils;
import cn.sciento.starter.tenant.custom.annotation.TenantCustom;
import cn.sciento.starter.tenant.custom.annotation.TenantCustomPoint;
import cn.sciento.starter.tenant.custom.repository.TenantCustomPointRepository;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

public class TenantCustomRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
  private final TenantCustomPointRepository tenantCustomPointRepository;
  
  private final String serviceName;
  
  public TenantCustomRequestMappingHandlerMapping(TenantCustomPointRepository tenantCustomPointRepository, String serviceName) {
    this.tenantCustomPointRepository = tenantCustomPointRepository;
    this.serviceName = serviceName;
  }
  
  protected RequestCondition<?> getCustomMethodCondition(Method method) {
    method.setAccessible(true);
    TenantCustom tenantCustom = AnnotationUtils.findAnnotation(method.getDeclaringClass(), TenantCustom.class);
    if (tenantCustom == null)
      return null; 
    TenantCustomPoint tenantCustomPoint = MethodUtils.getAnnotation(method, TenantCustomPoint.class, true, true);
    if (tenantCustomPoint == null)
      return null; 
    return new TenantCustomRequestCondition(this.serviceName + "." + tenantCustom.value() + "." + tenantCustomPoint.value(), this.serviceName, this.tenantCustomPointRepository);
  }
}
